package servicedevmap

import (
	"emsctrl/db"
	"emsctrl/public"
)

var (
	METER_YGGL = "yggl"
)

type meterdevMap struct {
	meterNum int
	yggl     float32
}

var meterMap map[string]map[string]string

func init() {
	meterMap = make(map[string]map[string]string)
}

func (b *meterdevMap) Analysis_string(info []string) {
	var ytype string
	var key string
	var mapv string
	for i, s := range info {
		switch i {
		case 0:
			break
		case 1:
			ytype = s
		case 2:
			key = s
		case 3:
			mapv = s
		}
	}

	if _, ok := meterMap[ytype]; ok {

	} else {
		meterMap[ytype] = make(map[string]string)
	}
	meterMap[ytype][key] = mapv
}

func (b *meterdevMap) upGradeDevData(index int, devtype, devname, paratype string, datum public.DataVal) {
	reg := StationMap[index][devtype][devname]

	if _, ok := meterMap[paratype]; ok {
		switch meterMap[paratype][datum.Key] {
		case METER_YGGL:
			if reg.RegMap == nil {
				reg.RegMap = make(map[string]RegInfo)
			} else {

			}
			if _, ok1 := reg.RegMap[meterMap[paratype][datum.Key]]; ok1 {
				info := reg.RegMap[meterMap[paratype][datum.Key]]
				info.Val = datum.Val
				info.Addr = datum.RegAddr
				info.PType = paratype
				reg.RegMap[meterMap[paratype][datum.Key]] = info
			} else {
				reg.RegMap[meterMap[paratype][datum.Key]] = RegInfo{Key: datum.Key, Val: datum.Val, Addr: datum.RegAddr, PType: paratype}
			}
		default:
		}
	}
	StationMap[index][devtype][devname] = reg
}

func (b *meterdevMap) ReportMeterData(devname string, info RegInfo) {
	switch devname {
	case "gridmeter":
		power := db.GridPower{}
		power.Power.Power = info.Val
		db.Insert(&power)
	case "bmsmeter":
		power := db.BmsPower{}
		power.Power.Power = info.Val
		db.Insert(&power)
	}

}
func (b *meterdevMap) upGradeCurrPolicyPara(devtype, devName, paratype string) {
	*b = meterdevMap{}
	for _, m := range StationMap {
		if _, ok := m[devtype][devName]; ok {
			reg := m[devtype][devName]
			switch devName {
			case "gridmeter":
				for s, info := range reg.RegMap {
					switch s {
					case METER_YGGL:
						G_curr_policy.RemoteMetering.GridActivePower = info.Val
						b.yggl = info.Val
						b.ReportMeterData(devName, info)
					}
				}
			case "bmsmeter":
				for s, info := range reg.RegMap {
					switch s {
					case METER_YGGL:
						G_curr_policy.RemoteMetering.BmsActivePower = info.Val
						b.yggl = info.Val
						b.ReportMeterData(devName, info)
					}
				}
			}
		}
	}
}
